<template>
  <a-modal
    title='新增页面'
    :width='900'
    :visible='visible'
    :confirmLoading='loading'
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning='loading'>
      <a-form :form='form' v-bind='formLayout'>
        <a-form-item label='选择模板'>
          <div class='template-list' v-decorator="[
              'templateId',
              { rules: [{ required: true, message: '请选择模板!' }] },
            ]">
            <div class='template-item' :class='{active: templateIndex === item }' v-for='item in 8' :key='item'
                 @click='handleSelectTemplate(item)'>
              <div class='img-container'>
                <!--TODO:模板缩略图-->
              </div>
              <p class='template-name'>空白模板</p>
            </div>
          </div>
        </a-form-item>
        <a-form-item label='页面名称'>
          <a-input v-decorator="[
              'view_name',
              { rules: [{ required: true, message: '请输入页面名称!' }] },
            ]" />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'

const fields = ['templateId', 'view_name']

export default {
  name: 'creatRealform',
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  components: {},
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 21 }
      }
    }
    return {
      templateIndex: 0,
      form: this.$form.createForm(this)
    }
  },
  created () {
    fields.forEach(v => this.form.getFieldDecorator(v))
    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
  },
  methods: {
    handleSelectTemplate (index) {
      this.templateIndex = index
      this.form.setFieldsValue({
        ...pick(this.model, fields),
        templateId: this.templateIndex
      })
    }
  }
}
</script>

<style lang='less' scoped>
.template-list {
  display: flex;
  flex-wrap: wrap;
  height: 300px;
  overflow: auto;
}

.template-item {
  width: 156px;
  height: 105px;
  display: flex;
  flex-direction: column;
  box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
  margin: 15px;
  padding: 10px;
  cursor: pointer;

  &.active {
    border: solid 1px rgba(65, 171, 251, 1);
    box-shadow: rgba(65, 171, 251, 1) 0px 3px 8px;
  }

  .img-container {
    flex: 1;
    background-color: red;
  }

  .template-name {
    width: 156px;
    height: 18px;
    margin-bottom: 5px;
  }

  img {
    object-fit: cover;
    flex: 1;
  }
}
</style>